﻿using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.CultureSwitcher.Handlers;
using Orchard.CultureSwitcher.Models;
using Orchard.CultureSwitcher.Services;
using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.UI.Notify;

namespace Orchard.CultureSwitcher.Drivers
{
    public class SwitcherSettingsPartDriver : ContentPartDriver<SwitcherSettingsPart>
    {
        private readonly INotifier _notifier;
        private readonly ISwitcherSettingsService _settingsService;

        public SwitcherSettingsPartDriver(INotifier notifier, ISwitcherSettingsService settingsService)
        {
            _notifier = notifier;
            _settingsService = settingsService;
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        protected override string Prefix
        {
            get { return "SwitcherSettings"; }
        }

        protected override DriverResult Editor(SwitcherSettingsPart part, dynamic shapeHelper)
        {
            part.CultureOrderedList = _settingsService.GetOrderedCulturesList();

            return ContentShape(
                "Parts_Switcher_Settings",
                () => shapeHelper.EditorTemplate(
                    TemplateName: "Parts/Switcher.Settings",
                    Model: part,
                    Prefix: Prefix)
            ).OnGroup(SwitcherSettingsHandler.SETTINGS_GROUP_ID);
        }

        protected override DriverResult Editor(SwitcherSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            if (updater.TryUpdateModel(part, Prefix, null, null))
            {
                _settingsService.UpdateCultureOrdering(part.CultureOrderedList);
                _notifier.Information(T("Update complete successfully!"));
            }
            else
            {
                _notifier.Information(T("Error during updating your part!"));
            }
            return Editor(part, shapeHelper);
        }
    }
}